// index.js
// 获取应用实例
const app = getApp()
Page({
  data: {
    cardsArr: [[],[],[],[]],
    cardsBox: [],
    cardsUrl: ['/static/img/beier.jpg', '/static/img/bingjie.jpg', '/static/img/dafei.jpg', '/static/img/jielatuoni.jpg', '/static/img/olu.jpg', '/static/img/xingdailu.jpg', '/static/img/xuelimei.jpg'],
    cardsName:['beier','bingjie','dafei','jielatuoni','olu','xingdailu','xuelimei'],
    cardsSetMode:['x','y','xy'],//卡片放的位置，左右，上下 和边角
    gameState:null // 1.游戏胜利 2.游戏结束
  },
  onShow: function () {
    this.initCards()
  },
  //卡牌对象
  // obj = {
  //   id: '',
  //   carName:'',
  //   y: null,//y坐标
  //   x: null,//x坐标
  //   zIndex:null,
  //   useCell: [],//占用格子
  //   positionTop:null,//绝对定位距离顶部
  //   positionLeft:null,//绝对定位距离左侧
  //   state:1,//1.不可选2.可选3.待消除4.已消除
  // }
  initCards: function () {
    this.data.cardsArr = []
    this.data.cardsBox = []
    this.setData({gameState:null})
    //渲染第一层得牌
    this.data.cardsArr.push([])
    for (let i = 0; i < 80; i++) {
      let obj = {}
      let x = this.randomNum(16)//取小于16得随机数
      let y = this.randomNum(16)//取小于16得随机数
      obj.y = y % 2 == 0 ? y + 1 : y //y坐标必须为小于16得奇数
      obj.x = x % 2 == 0 ? x + 1 : x //x坐标必须为小于16得奇数
      obj.zIndex = 0
      Object.assign(obj, this.generateCards(obj.x, obj.y))
      obj.state = 1
      //检测是否重叠在一起
      let pushFlag = this.data.cardsArr[0].some(item => item.x == obj.x && item.y == obj.y)
      if (!pushFlag) {
        this.data.cardsArr[0].push(obj)
      }
    }
    for(let i=0;i<4;i++){
      this.data.cardsArr.push([])
      let canUsePoint = this.checkCanUsePoint(this.data.cardsArr[i], this.data.cardsSetMode[this.randomNum(3)])
      canUsePoint.forEach(item => {
        let random = Math.random()
        if (random < 0.5) {
          let obj = {}
          obj.x = Number(item.split(",")[0])
          obj.y = Number(item.split(",")[1])
          obj.zIndex = i+1
          Object.assign(obj, this.generateCards(obj.x, obj.y))
          obj.state = 1
          this.data.cardsArr[i+1].push(obj)
        }
      })
    }
    //顶层卡片为可选择状态
    this.data.cardsArr[this.data.cardsArr.length-1].map(item=>{
      item.state = 2
    })
    this.setData({
      cardsArr: this.data.cardsArr
    })
    console.log(this.data.cardsArr)
    this.checkCardsState()
  },

  //检测可用的点
  checkCanUsePoint: function (arr, type) {
    let canUseArr = []
    arr.forEach(item => {
      let x = Number(item.x)
      let y = Number(item.y)
      if(x+1>=16||y+1>=16||x-1<=0||y-1<=0) return
      if (type == 'x') {
        canUseArr.push(x + 1 + ',' + y)
        canUseArr.push(x - 1 + ',' + y)
      } else if (type == 'y') {
        canUseArr.push(x + ',' + (y + 1))
        canUseArr.push(x + ',' + (y - 1))
      } else if (type == 'xy' || !type) {
        canUseArr.push((x + 1) + ',' + (y + 1))
        canUseArr.push((x - 1) + ',' + (y + 1))
        canUseArr.push((x + 1) + ',' + (y - 1))
        canUseArr.push((x - 1) + ',' + (y - 1))
      }
    });
    //去除重复的点
    canUseArr = [...new Set(canUseArr)]
    return canUseArr
  },

  //生成随机数
  randomNum: function (sum) {
    return Math.floor(Math.random() * sum)
  },
  //计算卡牌坐标与所占用的格子与生成id与name
  generateCards: function (x, y) {
    let obj = {}
    obj.id = String(new Date().getTime()) + Math.random().toString().slice(-5)
    let cardIndex = this.randomNum(7)
    obj.cardName = this.data.cardsName[cardIndex]
    obj.cardUrl = this.data.cardsUrl[cardIndex]
    obj.useCell = []
    //将一张图片看成四个格子 usecell数组四个数分别为左上、右上、左下、右下，并且格子序号为从左往右从上往下按顺序数的
    //（4,2）
    obj.useCell[0] = (y - 1) * 16 + (x - 1)
    obj.useCell[1] = (y - 1) * 16 + x
    obj.useCell[2] = (y - 1) * 16 + x + 15
    obj.useCell[3] = (y - 1) * 16 + x + 16
    //计算卡片的位置:左上角为(0,0)坐标
    obj.positionLeft = (x - 1) * 40
    obj.positionTop = (y - 1) * 40
    return obj
  },
  //检测卡片的状态
  checkCardsState: function (carObj) {
    //存放卡片所占用的格子
    let occupyCell = []
    this.data.cardsArr.map((item,index)=>{
      //存放当层可选与不可选的卡片
      if(index!=0){
        let bigBoxCards = item.filter(v => v.state == 1 || v.state == 2)
        occupyCell.push([])
        bigBoxCards.map(v=>{
          //检测每一层未选和不可选的卡片所占用的格子
          v.useCell.map(e=>{
            occupyCell[index-1].push(e)
          })
        })
      }
    })
    if(!carObj){
      this.data.cardsArr.map((item,index)=>{
        //检测每一层的卡片是否又被上层的卡片压着
        if(index!=this.data.cardsArr.length-1){
          item.map(items=>{
            let itemFlag = true
            let useCell = []
            for(let i=0;i<occupyCell.length;i++){
              if(i>=index){  
                useCell = useCell.concat(occupyCell[i])
              }
            }
            //去除重复的点
            useCell = [...new Set(useCell)]
            items.useCell.map(v=>{
              if(useCell.some(e=>e==v)){
                itemFlag = false
              }
            })
            if(itemFlag&&items.state==1){
              items.state = 2
            }
          })
        }
      })
    }else{
      if(carObj.zIndex>0) {
        this.data.cardsArr[carObj.zIndex-1].map((item)=>{
          let itemFlag = true
          let useCell = []
          for(let i=0;i<occupyCell.length;i++){
            if(i>=carObj.zIndex-1){  
              useCell = useCell.concat(occupyCell[i])
            }
          }
          item.useCell.map(v=>{
            if(useCell.some(e=>e==v)){
              itemFlag = false
            }
          })
          if(itemFlag&&item.state==1){
            item.state = 2
          }
        })
      }
    }
    
    this.setData({ cardsArr: this.data.cardsArr })

  },
  //检测盒子容器
  checCardskBox:function (cardObj) {
    let checkArr = this.data.cardsBox.filter(item=>item.cardName==cardObj.cardName)
    if(checkArr.length==3){
      checkArr.map(item=>{
        //寻找卡片的位置
        this.data.cardsArr[item.zIndex].map(v=>{
          if(item.id==v.id){
            v.state = 4
          }
        })
        //会引起页面的刷新，舍弃
        // this.data.cardsArr[item.zIndex].splice(this.data.cardsArr[item.zIndex].findIndex(v=>item.id==v.id),1)
      })
      this.setData({ cardsBox: this.data.cardsBox.filter(item=>item.cardName!=cardObj.cardName) })
      //重新计算每张卡片的位置
      this.data.cardsBox.map((item,index)=>{
        this.data.cardsArr[item.zIndex].map((v)=>{
          if(item.id==v.id){
            item.positionTop = 700
            item.positionLeft = 40 + index * 80
          }
        })
      })
      this.setData({ cardsArr: this.data.cardsArr })
    }
    this.checkGameState()
  },
  checkGameState(){
    let isWin = true
    this.data.cardsArr.map(item=>{
      if(!item.every(v=>v.state==4)){
        isWin = false
      }
    })
    let isLose = this.data.cardsBox.length>=7
    if(isWin){
      this.setData({gameState:1})
    }
    if(isLose){  
      this.setData({gameState:2})
    }
  },
  //点击卡片触发事件
  hanlderCards: function (e) {
    let cardObj = e.currentTarget.dataset.cardDetail
    if (cardObj.state != 2 || this.data.cardsBox.length >= 7) {
      return
    }
    this.data.cardsArr[cardObj.zIndex].map(item => {
      if (item.id == cardObj.id) {
        item.state = 3
        item.positionTop = 700
        item.positionLeft = 40 + this.data.cardsBox.length * 80
        this.data.cardsBox.push(item)
        this.setData({ cardsArr: this.data.cardsArr })
        this.checkCardsState(item)
        this.checCardskBox(item)
      }
    })
  },

})
